package com.hui.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hui.config.Result;
import com.hui.entity.User;
import com.hui.mapper.UserMapper;
import com.hui.service.UserService;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @BelongsProject: bilibili-qingGe
 * @BelongsPackage: com.hui.controller
 * @Author: HUI
 * @CreateTime: 2021-12-02 14:30
 * @Description:
 */

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;


    //新增用户
    @PostMapping
    public Result<?> saveUser(@RequestBody User user) {
//        System.out.println(user);
        //如果密码为空

        User users = userService.addQuery(user);
        if (users != null) {
            return Result.error("-1", user.getUsername() + "用户已存在！");
        } else {
            user.setPassword(user.getPassword() == null || user.getPassword().isEmpty() ? "admin" : user.getPassword());

            int save = userService.saveUser(user);
            return save > 0 ? Result.success(user.getUsername()) : Result.error("-1", user.getUsername() + "插入失败！");

        }


    }

    //修改用户
    @PutMapping
    public Result<?> updateUser(@RequestBody User user) {
        int update = userService.updateUser(user);
        return update > 0 ? Result.success(user.getUsername()) : Result.error("-1", user.getUsername() + "更新失败！");
    }


    //分页查询数据
    @GetMapping
    public Result<?> queryUser(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(defaultValue = "") String searchStr
    ) {

        return Result.success(userService.queryUser(pageNum, pageSize, searchStr));
    }


    //删除
    @DeleteMapping
    public Result<?> deleteUser(@RequestParam Integer id) {
        int delete = userService.deleteUser(id);
        return delete > 0 ? Result.success() : Result.error("-1", "删除失败");
    }


    //登录
    @PostMapping("/login")
    public Result<?> loginUser(@RequestBody User user) {

        User loginUser = userService.loginUser(user);


        return loginUser == null ? Result.error("-1", "账号或密码错误") : Result.success(loginUser);

       /* if (loginUser == null) {
            return Result.error("-1", "账号或密码错误");
        }

        return Result.success(loginUser.getUsername());
*/
    }


    //查询当前登录的用户信息
    @GetMapping("/own")
    public Result<?> queryOwn(@RequestParam Integer id) {
        User user = userService.queryOwn(id);
        return user != null ? Result.success(user) : Result.error("-1", "没有该用户");

    }

}
